import React, { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { Button, Space, Swiper, Toast, SearchBar, Grid, PullToRefresh, List, InfiniteScroll } from 'antd-mobile'
import type { BannerListData, MenuListData, GoodsListData } from '../../types/home'
import { getBannerList, getMenuList, getGoodsList } from '../../api/Home'
import { UserOutline, AppstoreOutline } from 'antd-mobile-icons'
import { sleep } from 'antd-mobile/es/utils/sleep'

export default function useIndex() {
  const [swiperList, setSwiperList] = useState<Array<BannerListData>>([] as BannerListData[])
  const [menuList, setMenuList] = useState<MenuListData[]>([] as MenuListData[])
  let [goodsList, setGoodsList] = useState<GoodsListData[]>([] as GoodsListData[])
  const [scrollTop, setscrollTop] = useState(window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop)
  const [headSc, setHeadSc] = useState<boolean>(true)
  let [total, setTotal] = useState<number>(0)
  let [isFinish, setFinish] = useState<boolean>(false)
  let isReflase = false

  const [isError, setIsError] = useState(true)
	const defaultImg = ''
	const imgerrorfun = (event:any) => {
			setIsError(false);
			event.target.src = defaultImg;
	}

  const getSwiperData = async () => {
    const res = await getBannerList()
    console.log(res);
    setSwiperList(res.data)
  }
  const items = swiperList.map((item, index) => (
    <Swiper.Item key={index}>
      <img src={item.img} style={{ width: "100%", height: "100%" }}></img>
    </Swiper.Item>
  ))
  const getMenuLists = async () => {
    const res = await getMenuList()
    setMenuList(res.data)
  }
  
  const menus = menuList.map((item, index) => (
    <Swiper.Item key={index} className='grids'>
      <img src={item.icon}></img>
      <div>{item.title}</div>
    </Swiper.Item>
  ))

  const getGoodsData = async () => {
    const res = await getGoodsList(total + 1)
    // if (isReflase === true) {
    //   const res = await getGoodsList(1)
    //   setGoodsList(res.data)
    //   isReflase = false
    // } else {
    //   setGoodsList([...goodsList, ...res.data])
    // }
    setGoodsList([...goodsList, ...res.data])
    setTotal(total + 1)
    if (res.data.length === 0) {
      setFinish(true)
    }
  }

  const goods = goodsList.map((item, index) =>
    <Swiper.Item key={index} className='good-item'>
      <Link to={`./goodde?proid=${item.proid}`}>
        <img src={item.img1} onError={imgerrorfun}></img>
        <div className="good-desc">
          <div className="title">{item.brand}</div>
          <span className="desc">{item.desc}</span>
          <div className="price">¥ {item.originprice}</div>
        </div>
      </Link>
    </Swiper.Item>
  )

  const onRefresh = async () => { //下拉刷新
    isReflase = true
    setTotal(0)
    setGoodsList([])
  }

  const onEndReached = async (event: any) => {//触底加载
    if (isFinish) {
      return;
    }
    getGoodsData()
  }

  const scrThing = () => {
    setscrollTop(window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop)
  }

  //初始化
  useEffect(() => {
    getSwiperData()
    getMenuLists()
    getGoodsData()
    window.addEventListener('scroll', scrThing)

    return () => window.removeEventListener("scroll", scrThing)
  }, [])

  useEffect(() => {
    scrollTop > 100 ? setHeadSc(true) : setHeadSc(false)
  }, [scrollTop])
  return (
    <div style={{ paddingBottom: "50px" }}>
      <PullToRefresh
        onRefresh={async () => {
          await sleep(1000)
          onRefresh()
        }}
      >
        <header className={`home-header wrap ${headSc ? "active" : ''}`}>
          <Link to="./category"><i className="nbicon nbmenu2"><AppstoreOutline /></i></Link>
          <div className="header-search">
            <span className="app-name">牛马商城</span>
            <i className="iconfont icon-search"></i>
            <Link className="search-title" to="/search">山河无恙，人间皆安</Link>
          </div>
          <Link className="login" to="/login" v-if="!state.isLogin">登录</Link>
          <Link className="login" to="/mypage" v-else>
            <UserOutline />
          </Link>
        </header>
        <Swiper
          style={{ '--height': '200px' }}
          className='adm-swiper' loop
          autoplay>
          {items}
        </Swiper>
        <Grid columns={5} className="category-list" gap={0}>
          {menus}
        </Grid>
        <div className="good-header">精选商品</div>
        <div className="good">
          <Grid columns={2} className="good-box" gap={0}>
            {goods}
          </Grid>
        </div >
        <InfiniteScroll loadMore={onEndReached} hasMore={!isFinish} threshold={100} />
      </PullToRefresh>
    </div >
  )
}
